<template>
  <div>
    <!-- 卡片视图区 -->
    <el-card class="box-card">
      <!-- 面包屑导航区 -->
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>资源管理</el-breadcrumb-item>
        <el-breadcrumb-item>课程表管理</el-breadcrumb-item>
      </el-breadcrumb>

    <!-- 搜索区 -->
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input
            placeholder="请输入需要搜索的课程"
            v-model="queryInfo.query"
            clearable>
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="searchTimeTable">
            </el-button>
          </el-input>
        </el-col>
        <el-col :span="2">
          <el-button type="primary" @click="addTimeTable">添加课程表</el-button>
        </el-col>
        <el-col :span="2">
          <el-button type="danger" @click="batchDelTimeTable">批量删除</el-button>
        </el-col>
      </el-row>

      <!-- 课程表表格区 -->
      <el-table
        :header-cell-style="{textAlign: 'center'}"
        :cell-style="{ textAlign: 'center' }"
        :data="tableData"
        @selection-change="handleSelectionChange"
        border
        style="width: 100%">
        <el-table-column
          type="selection"
          width="55">
        </el-table-column>
        <el-table-column
          prop="id"
          label="序号"
          width="100">
        </el-table-column>
        <el-table-column
          prop="class_order"
          label="排序"
          width="100">
        </el-table-column>
        <el-table-column
          prop="class_name"
          label="课程名"
          width="300">
        </el-table-column>
        <el-table-column
          label="图片"
          width="550">
          <template slot-scope='scope'>
            <div class="demo-image__preview">
              <el-image 
                style="width: 150px"
                :src="scope.row.url"
                :preview-src-list="allTimeTableList">
              </el-image>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button 
              type="primary" 
              icon="el-icon-edit" 
              size="mini"
              @click="editTimeTable(scope.row)"></el-button>
            <el-button 
              type="danger" 
              icon="el-icon-delete" 
              size="mini" 
              @click="delTimeTable(scope.row.id)"></el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pageNum"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        background>
      </el-pagination>
    </el-card>

    <!-- 操作课程表对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="opeDialogVisible"
      width="50%">
      <el-form
        :model="opeForm"
        v-loading="loading"
        element-loading-text="拼命上传课表中"
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.8)"
        ref="opeFormRef"
        label-width="100px">
        <el-form-item label="课程名" prop="class_name">
          <el-input v-model="opeForm.class_name"></el-input>
        </el-form-item>
        <el-form-item label="排序" prop="class_order">
          <el-input v-model="opeForm.class_order"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="opeForm.remark"></el-input>
        </el-form-item>
        <el-upload
          drag
          v-if="this.title=='添加课程表' ? true : false"
          class="addTimeTable"
          ref="addTimeTableRef"
          :file-list="addList"
          :auto-upload='false'
          :before-upload="beforeAddUpload"
          :on-success='onSuccess'
          :action="addURL"
          list-type="picture"
          :limit=1>
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将图片拖到此处，或<em>点击上传</em></div>
        </el-upload>
        <el-form-item
          v-if="this.title=='修改课程表' ? true : false">
          <div class="demo-image__preview">
            <el-image 
              :src="editImagePreURL"
              :preview-src-list="editImagePreList">
            </el-image>
          </div>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-upload
          v-if="this.title=='修改课程表' ? true : false"
          class="editTimeTable"
          ref='editTimeTableRef'
          :file-list="editList"
          :auto-upload='false'
          :before-upload="beforeEditUpload"
          :on-success="onSuccess"
          :on-change="editChange"
          list-type="picture"
          :action="editURL"
          :limit="1">
          <el-button type="info">点击上传新图片</el-button>
        </el-upload>
        <el-button @click="opeDialogVisible = false">取 消</el-button>
        <el-button type="primary" v-loading="loading" @click="operation">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  created() {
    this.getAllTimeTable()
  },
  data() {
    return {
      queryInfo: {
        pageNum: 1,
        pageSize: 5,
        query: ''
      },
      tableData: [],
      total: 0,
      title: '',

      opeDialogVisible: false,
      opeForm: {
        class_name: '',
        class_order: 0,
        id: 0,
        url: '',
        remark: ''
      },

      ids: [],

      allTimeTableList: [],

      editImagePreList: [],
      editImagePreURL: '',

      loading: false,

      addList: [],
      editList: [],
      addURL: 'http://121.196.185.217:8444/insertJxTimeTable',
      editURL: 'http://121.196.185.217:8444/updateJxTimeTable',

      isEdit: false
    }
  },
  methods: {
    // 获取所有的课程表
    async getAllTimeTable() {
      const { data: res } = await this.$http.post('findAllJxTimeTable', this.queryInfo)
      if (res.code != 'success') return this.$message.error('获取课程表失败')
      this.tableData = res.data
      this.total = res.numbers
      res.data.forEach(item => this.allTimeTableList.push(item.url))
      this.$message.success('获取课程表成功')
    },
    // 添加课程表按钮被点击后
    addTimeTable() {
      this.title = '添加课程表'
      this.opeForm.class_name = ''
      this.opeForm.class_order = 0
      this.opeForm.remark = ''
      this.opeDialogVisible = true
    },
    // 修改课程表按钮被点击后
    editTimeTable(timeTable) {
      this.title = '修改课程表'
      this.opeForm.class_name = timeTable.class_name
      this.opeForm.class_order = timeTable.class_order
      this.opeForm.remark = timeTable.remark
      this.opeForm.id = timeTable.id
      this.editImagePreList = []
      this.editImagePreList.push(timeTable.url)
      this.editImagePreURL = timeTable.url
      this.opeDialogVisible = true
    },
    // 当修改课程表的图片时
    editChange(file, fileList) {
      this.isEdit = true
    },
    // 发送添加、修改课程表的请求
    async operation() {
      // 此处并未判断添加课程表的图片是否为空
      this.loading = true
      if (this.title == '添加课程表') {
        return new Promise((resolve, reject) => {
          this.$nextTick(() => { 
            this.$refs.addTimeTableRef.submit()
          })
        })
      } else {
        if (this.isEdit === false) {
          const { data: res } = await this.$http.post(`/updateJxTimeTable?id=${this.opeForm.id}&className=${this.opeForm.class_name}&classOrder=${this.opeForm.class_order}&remark=${this.opeForm.remark}`)
          if (res != 'success') return this.$message.error('修改课程表失败')
          this.$message.success('修改课程表成功')
          this.loading = false
          this.opeDialogVisible = false
          this.getAllTimeTable()
        } else {
          return new Promise((resolve, reject) => {
          this.$nextTick(() => {
            this.$refs.editTimeTableRef.submit()
          })
        })
        }
      }
      
    },
    // 在添加课程表图片上传之前
    beforeAddUpload() {
      this.addURL = 'http://121.196.185.217:8444/insertJxTimeTable'
      return new Promise((resolve, reject) => {
        this.$nextTick(() => {
          this.addURL = this.addURL+'?'+'className='+this.opeForm.class_name
          this.addURL = this.addURL+'&'+'classOrder='+this.opeForm.class_order
          this.addURL = this.addURL+'&'+'remark='+this.opeForm.remark
          resolve()
        })
      })
    },
    // 在修改课程表图片上传之前
    beforeEditUpload() {
      this.editURL = 'http://121.196.185.217:8444/updateJxTimeTable'
      return new Promise((resolve, reject) => {
        this.$nextTick(() => {
          this.editURL = this.editURL+'?'+'id='+this.opeForm.id
          this.editURL = this.editURL+'&'+'className='+this.opeForm.class_name
          this.editURL = this.editURL+'&'+'classOrder='+this.opeForm.class_order
          this.editURL = this.editURL+'&'+'remark='+this.opeForm.remark
          resolve()
        })
      })
    },
    // 添加成功后
    onSuccess() {
      this.opeDialogVisible = false
      this.loading = false
      if (this.title == '添加课程表') {
        this.$message.success('添加课程表成功')
      } else {
        this.$message.success('修改课程表成功')
      }
      this.getAllTimeTable()
    },
    // 单个删除课程表
    async delTimeTable(id) {
      const confirmResult = await this.$confirm('此操作将永久删除该课程表, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult !== 'confirm') return this.$message.info('已取消删除')
      const { data: res } = await this.$http.post('deleteJxTimeTable', { ids: id })
      if (res !== 'success') return this.$message.error('删除课程表失败')
      this.$message.success('删除课程表成功')
      this.getAllTimeTable()
    },
    // 批量删除课程表
    async batchDelTimeTable() {
      const confirmResult = await this.$confirm('此操作将永久删除这些课程表, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult !== 'confirm') return this.$message.info('已取消删除')
      const { data: res } = await this.$http.post('deleteJxTimeTable', { ids: this.ids.join(',') })
      if (res !== 'success') return this.$message.error('删除课程表失败')
      this.$message.success('删除课程表成功')
      this.getAllTimeTable()
    },
    // 搜索课程表
    async searchTimeTable() {
      const { data: res } = await this.$http.post('findAllJxTimeTable', this.queryInfo)
      if (res.code !== 'success') return this.$message.error('查询课程表失败')
      this.$message.success('查询课程表成功')
      this.tableData = res.data
      this.total = res.numbers
      this.allTimeTableList = []
      res.data.forEach(item => this.allTimeTableList.push(item.url))
    },
    // 批量选择
    handleSelectionChange(val) {
      this.ids = []
      val.forEach(item => this.ids.push(item.id))
    },
    handleSizeChange(size) {
      this.queryInfo.pageSize = size
      this.getAllTimeTable()
    },
    handleCurrentChange(num) {
      this.queryInfo.pageNum = num
      this.getAllTimeTable()
    }
  }
}
</script>

<style scoped>
.addTimeTable {
  margin-left: 100px;
}

.editTimeTable {
  margin-bottom: 20px;
}
</style>